// pages/shopcart/shopcart.js
var common = require("../../common/common.js").common;

// var mta = require('../../sdk/mta_analysis.js');
var util = require("../../utils/util.js");

var app = getApp();

var {$author: $author} = require("../../components/base/authorization.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        localNum: 0,
        repeatBind: false,
        loading: true,
        domain: app.globalData.domain.slice(0, -10),
        localHeight: 0,
        //本地商家高度
        tip_active: 1,
        //--国际化--
        language: "",
        langIndex: 0,
        //--end--
        startX: 0,
        //开始坐标
        startY: 0,
        items: [],
        items2: [],
        sku_info: [],
        select_all: 0,
        money: 0,
        o_money: 0,
        discount: 0,
        detail: "",
        color_header: "",
        color_main: "",
        color_minor: "",
        color_gray: "#848484",
        tmplIds: [],
        //模板消息tmplIds
        subscribeMessage: true
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getBase();
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        if (options && options.group_id) {
            //接龙
            this.setData({
                group_id: options.group_id
            });
        }
        this.setData({
            tip_active: options.type ? options.type : 1,
            afferent: options.type ? 1 : 0
        });
        // mta.Page.init();
                this.getTmplIds();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        //首次直接进入，拿user_id
        if (app.globalData.user) {
            //如果直接拿到openid
            this.setData({
                uid: app.globalData.user.uid
            });
            wx.setStorageSync("user", app.globalData.user);
            this.vipStatus();
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                this.setData({
                    uid: res.uid
                });
                this.vipStatus();
            });
        }
        const system = wx.getSystemInfoSync().system;
        const isIOS = system.includes("iOS");
        this.setData({
            isIOS: isIOS
        });
    },
    changeScroll(e) {
        this.setData({
            tip_active: e.currentTarget.dataset.id
        });
        wx.pageScrollTo({
            scrollTop: e.currentTarget.dataset.id == 1 ? 0 : (this.data.localHeight - 20) / 2,
            duration: 300
        });
    },
    //进入商家
    toBusiness(e) {
        wx.navigateTo({
            url: "/localLifePackage/pages/businessInfo/businessInfo?merchant_id=" + e.currentTarget.dataset.id
        });
    },
    // 获取购物车列表
    getList() {
        let that = this;
        let leader_id = that.data.myleaderinfo ? that.data.myleaderinfo.leader_id : 0;
        that.setData({
            loading: true
        });
        common.request({
            endpoint: "Order/cart/view",
            method: "post",
            data: {
                leader_id: leader_id
            },
            success: res => {
                that.setData({
                    localPlist: res.extra.local_business,
                    platform: res.extra.platform,
                    loading: false
                });
                if (res.extra.local_business.length > 0) {
                    let num = 0;
                    res.extra.local_business.forEach(element => {
                        num += element.products.length;
                    });
                    that.setData({
                        localNum: num
                    });
                    let query = wx.createSelectorQuery();
                    query.select("#local").boundingClientRect(rect => {
                        let clientHeight = rect.height;
                        let clientWidth = rect.width;
                        let ratio = 750 / clientWidth;
                        let height = clientHeight * ratio;
                        that.setData({
                            localHeight: height
                        });
                        if (that.data.afferent == 1) {
                            wx.pageScrollTo({
                                scrollTop: (this.data.localHeight - 20) / 2,
                                duration: 300
                            });
                            that.setData({
                                afferent: 0
                            });
                        }
                    }).exec();
                } else {
                    that.setData({
                        localNum: 0
                    });
                }
                wx.stopPullDownRefresh();
            }
        });
    },
    confirmInput(e) {
        let that = this;
        console.log(e);
        if (!e.detail.value) {
            return;
        }
        let count = e.detail.value;
        common.request({
            endpoint: "Order/cart/add",
            method: "post",
            data: {
                sku_id: e.currentTarget.dataset.sku,
                type: 1,
                flag: 0,
                business_id: e.currentTarget.dataset.bussiness ? e.currentTarget.dataset.bussiness : 0,
                leader_id: that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : 0,
                num: count
            },
            success: res => {
                if (res.code == 0) {
                    that.getList();
                } else {
                    wx.showModal({
                        title: "提示",
                        content: res.message,
                        showCancel: false
                    });
                }
            },
            fail: res => {
                wx.showModal({
                    title: "提示",
                    content: res.message,
                    showCancel: false
                });
            }
        });
    },
    // 修改数量
    changeNum(e) {
        let that = this;
        let num = e.currentTarget.dataset.count;
        let type = e.currentTarget.dataset.type;
        var minimum_num = parseInt(e.currentTarget.dataset.minimumnum);
        var step_num = parseInt(e.currentTarget.dataset.stepnum);
        var single = e.currentTarget.dataset.single;
        var minimum_num = single == 1 ? parseInt(e.currentTarget.dataset.minimumnum) : 1;
        var step_num = single == 1 ? parseInt(e.currentTarget.dataset.stepnum) : 1;
        if (type == "add") {
            num = parseInt(num) + step_num;
        } else if (type == "min") {
            if (num > minimum_num) {
                num = parseInt(num) - step_num;
            } else {
                wx.showToast({
                    title: "该宝贝不能在减少了~",
                    icon: "none"
                });
                return;
            }
        } else {
            num = parseInt(num);
        }
        common.request({
            endpoint: "Order/cart/add",
            method: "post",
            data: {
                sku_id: e.currentTarget.dataset.sku,
                type: 1,
                flag: 0,
                business_id: e.currentTarget.dataset.bussiness ? e.currentTarget.dataset.bussiness : 0,
                leader_id: that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : 0,
                num: num
            },
            success: res => {
                if (res.code == 0) {
                    that.getList();
                } else {
                    wx.showModal({
                        title: "提示",
                        content: res.message,
                        showCancel: false
                    });
                }
            },
            fail: res => {
                wx.showModal({
                    title: "提示",
                    content: res.message,
                    showCancel: false
                });
            }
        });
    },
    //本地商家全选
    changeSelectA(e) {
        let index = e.currentTarget.dataset.index;
        let localPList = this.data.localPlist;
        let platList = this.data.platform.products;
        let source = e.currentTarget.dataset.source;
        let business_id = source == 1 ? localPList[index].business.id : 0;
        let status = e.currentTarget.dataset.status;
        if (status == 1) {
            status = 0;
        } else {
            status = 1;
        }
        let string = "";
        if (source == 1) {
            localPList[index].products.forEach(res => {
                if (res.status != 0) {
                    string = string + res.item_id + ",";
                }
            });
        } else {
            platList.forEach(res => {
                if (res.status != 0) {
                    string = string + res.item_id + ",";
                }
            });
        }
        let sku = string.slice(0, -1);
        this.changeS(status, business_id, sku);
    },
    // 本地商家单选
    changeSelectO(e) {
        let status = e.currentTarget.dataset.status;
        let sku = e.currentTarget.dataset.sku;
        let business_id = e.currentTarget.dataset.business;
        if (status == 1) {
            status = 0;
        } else {
            status = 1;
        }
        this.changeS(status, business_id, sku);
    },
    changeS(status, business_id, sku) {
        let that = this;
        common.request({
            endpoint: "Order/cart/checked",
            method: "post",
            data: {
                leader_id: that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : 0,
                sku_id: sku,
                business_id: business_id,
                status: status
            },
            success: res => {
                that.getList();
            }
        });
    },
    // 本地商家单个删除
    delO(e) {
        let business_id = e.currentTarget.dataset.business;
        let sku = e.currentTarget.dataset.sku;
        this.delR(business_id, sku);
    },
    // 本地商家多个删除
    delA(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        let source = e.currentTarget.dataset.source;
        let business_id = source == 1 ? that.data.localPlist[index].business.id : 0;
        let list = source == 1 ? that.data.localPlist[index].products : that.data.platform.products;
        let string = "";
        list.forEach(item => {
            if (item.checked == 1) {
                string = string + item.item_id + ",";
            }
        });
        if (string == "") {
            return false;
        }
        let sku = string.slice(0, -1);
        that.delR(business_id, sku);
    },
    delR(business_id, sku) {
        let that = this;
        common.request({
            endpoint: "Order/cart/delete",
            method: "post",
            data: {
                business_id: business_id,
                sku_id: sku,
                leader_id: that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : 0
            },
            success: res => {
                wx.showToast({
                    title: "删除成功",
                    icon: "success",
                    duration: 2e3
                });
                that.getList();
            }
        });
    },
    vipStatus: function() {
        var that = this;
        common.request({
            endpoint: "vipcard/vip-verify",
            method: "post",
            data: {},
            success: res => {
                var vipStatus = res.extra.vip_card;
                if (vipStatus == 1 || vipStatus == 2 || vipStatus == 3) {
                    //会员卡 0-没有 1-付费 2-消费 3-体验 -1-过期
                    vipStatus = 1;
                } else {
                    vipStatus = 0;
                }
                that.setData({
                    vipStatus: vipStatus
                });
                that.getMyLeaderInfo();
            },
            fail() {
                that.getMyLeaderInfo();
            }
        });
    },
    getMyLeaderInfo: function() {
        var that = this;
        common.request({
            endpoint: "leader/myleaderinfo",
            method: "post",
            data: {
                openid: wx.getStorageSync("user").openid
            },
            success: res => {
                that.setData({
                    myleaderinfo: res.extra
                });
                that.getList();
                that.getData();
            },
            fail() {
                that.getData();
            }
        });
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        this.getList();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    //手指触摸动作开始 记录起点X坐标
    touchstart: function(e) {
        //开始触摸时 重置所有删除
        this.data.items.forEach(function(v, i) {
            if (v.isTouchMove) //只操作为true的
            v.isTouchMove = false;
        });
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            items: this.data.items
        });
    },
    //滑动事件处理
    touchmove: function(e) {
        var that = this, index = e.currentTarget.dataset.index, //当前索引
        startX = that.data.startX, //开始X坐标
        startY = that.data.startY, //开始Y坐标
        touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
        touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
        //获取滑动角度
        angle = that.angle({
            X: startX,
            Y: startY
        }, {
            X: touchMoveX,
            Y: touchMoveY
        });
        that.data.items.forEach(function(v, i) {
            v.isTouchMove = false;
            //滑动超过30度角 return
                        if (Math.abs(angle) > 30) return;
            if (i == index) {
                if (touchMoveX > startX) //右滑
                v.isTouchMove = false; else //左滑
                v.isTouchMove = true;
            }
        });
        //更新数据
                that.setData({
            items: that.data.items
        });
    },
    /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
    angle: function(start, end) {
        var _X = end.X - start.X, _Y = end.Y - start.Y;
        //返回角度 /Math.atan()返回数字的反正切值
                return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    //删除事件
    del: function(e) {
        this.data.items.splice(e.currentTarget.dataset.index, 1);
        var items = this.data.items;
        this.setData({
            items: this.data.items
        });
        wx.setStorage({
            key: "cart",
            data: items
        });
        let cart_count = 0;
        for (var i = 0; i < items.length; i++) {
            cart_count += Number(items[i]["count"]);
        }
        wx.setStorage({
            key: "cart_count",
            data: cart_count
        });
        var money = 0;
        var discount = 0;
        var o_money = 0;
        for (var j = 0; j < items.length; j++) {
            if (items[j]["select"] == 1) {
                money += parseFloat(items[j]["price"]) * items[j]["count"];
                o_money += parseFloat(items[j]["o_price"] * items[j]["count"]);
            }
        }
        discount = o_money - money;
        this.setData({
            money: money.toFixed(2),
            discount: discount.toFixed(2),
            o_money: o_money.toFixed(2)
        });
        let money_xx = that.data.order_start * 100 - that.data.money * 100;
        that.setData({
            money_xx: money_xx / 100
        });
        //提示删除成功
                wx.showToast({
            title: "删除成功",
            icon: "none"
        });
        this.startBuyCondition(money.toFixed(2));
    },
    //手指触摸动作开始 记录起点X坐标
    touchstart2: function(e) {
        //开始触摸时 重置所有删除
        this.data.items2.forEach(function(v, i) {
            if (v.isTouchMove) //只操作为true的
            v.isTouchMove = false;
        });
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            items2: this.data.items2
        });
    },
    //滑动事件处理
    touchmove2: function(e) {
        var that = this, index = e.currentTarget.dataset.index, //当前索引
        startX = that.data.startX, //开始X坐标
        startY = that.data.startY, //开始Y坐标
        touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
        touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
        //获取滑动角度
        angle = that.angle({
            X: startX,
            Y: startY
        }, {
            X: touchMoveX,
            Y: touchMoveY
        });
        that.data.items2.forEach(function(v, i) {
            v.isTouchMove = false;
            if (Math.abs(angle) > 30) return;
            if (i == index) {
                if (touchMoveX > startX) //右滑
                v.isTouchMove = false; else //左滑
                v.isTouchMove = true;
            }
        });
        //更新数据
                that.setData({
            items2: that.data.items2
        });
    },
    //删除事件
    del2: function(e) {
        this.data.items2.splice(e.currentTarget.dataset.index, 1);
        var items2 = this.data.items2;
        this.setData({
            items2: this.data.items2
        });
        wx.setStorage({
            key: "invalid",
            data: items2
        });
        //提示删除成功
                wx.showToast({
            title: "删除成功",
            icon: "none"
        });
    },
    empty_invalid: function() {
        this.setData({
            items2: []
        });
        var items2 = this.data.items2;
        wx.setStorage({
            key: "invalid",
            data: items2
        });
        //提示删除成功
                wx.showToast({
            title: "删除成功",
            icon: "none"
        });
    },
    getData: function() {
        var that = this;
        let goods = wx.getStorageSync("cart");
        let invalid = wx.getStorageSync("invalid") || [];
        if (that.data.group_id) {
            goods = goods.filter(item => {
                return item.group_id == that.data.group_id;
            });
        } else {
            goods = goods.filter(item => {
                return !item.group_id;
            });
        }
        let item_idBox = [];
        let items = [];
        let items2 = [];
        var leaderInfo = that.data.myleaderinfo;
        for (var i = 0; i < goods.length; i++) {
            item_idBox.push(goods[i].id);
        }
        for (var i = 0; i < invalid.length; i++) {
            for (var j = 0; j < goods.length; j++) {
                if (goods[j].id == invalid[i].id) {
                    break;
                } else if (j == goods.length - 1) {
                    goods.push(invalid[i]);
                    item_idBox.push(invalid[i].id);
                }
            }
        }
        var param = {};
        param["data"] = item_idBox;
        if (that.data.group_id) {
            param["group_id"] = that.data.group_id;
        }
        common.request({
            endpoint: "product/cart_num",
            method: "post",
            data: param,
            success: res => {
                var stock;
                var defaultPro = res.extra.default;
                var express = res.extra.express;
                //处理数据
                                if (defaultPro.length > 0) {
                    defaultPro.forEach((item, index) => {
                        item.proType = 0;
                    });
                }
                if (express.length > 0) {
                    express.forEach((item, index) => {
                        item.proType = 1;
                    });
                }
                //筛选平台商品
                                stock = defaultPro;
                for (var i = 0; i < stock.length; i++) {
                    goods.forEach((item, index) => {
                        if (item.id == stock[i].id) {
                            item.if = 0;
                            item.newst = 0;
                            item.o_price = stock[i].o_price;
                            item.price = stock[i].price;
                            item.proType = stock[i].proType;
                            item.spec_fund = stock[i].spec_fund;
                            item.only_vip = stock[i].only_vip;
                            if (stock[i].status == 1) {
                                if (stock[i].stock_number > 0) {
                                    if (stock[i].newst == 1) {
                                        if (stock[i].if == 1) {
                                            item.status = 1;
                                            item.stock_number = stock[i].stock_number;
                                            item.if = 1;
                                            item.newst = 1;
                                            items.push(item);
                                        } else {
                                            item.status = 1;
                                            item.stock_number = stock[i].stock_number;
                                            item.newst = 1;
                                            item.if = 0;
                                            items2.push(item);
                                        }
                                    } else {
                                        item.status = 1;
                                        item.stock_number = stock[i].stock_number;
                                        item.newst = 0;
                                        items2.push(item);
                                    }
                                } else {
                                    item.status = 1;
                                    item.stock_number = 0;
                                    items2.push(item);
                                }
                            } else {
                                item.status = 0;
                                items2.push(item);
                            }
                        }
                    });
                }
                //处理快递商品
                                for (var i = 0; i < express.length; i++) {
                    goods.forEach((item, index) => {
                        //如果选择了团长
                        if (leaderInfo) {
                            if (item.id == express[i].id) {
                                item.if = 0;
                                item.newst = 0;
                                item.o_price = express[i].o_price;
                                item.price = express[i].price;
                                item.proType = express[i].proType;
                                item.only_vip = express[i].only_vip;
                                if (express[i].status == 1) {
                                    if (express[i].stock_number > 0) {
                                        if (express[i].newst == 1) {
                                            if (express[i].if == 1) {
                                                item.status = 1;
                                                item.stock_number = express[i].stock_number;
                                                item.if = express[i].if == 1 ? 1 : 0;
                                                item.newst = 1;
                                                items.push(item);
                                            } else {
                                                item.status = 1;
                                                item.stock_number = express[i].stock_number;
                                                item.newst = 1;
                                                item.if = 0;
                                                items2.push(item);
                                            }
                                        } else {
                                            item.status = 1;
                                            item.stock_number = express[i].stock_number;
                                            item.newst = 0;
                                            items2.push(item);
                                        }
                                    } else {
                                        item.status = 1;
                                        item.stock_number = 0;
                                        items2.push(item);
                                    }
                                } else {
                                    item.status = 0;
                                    items2.push(item);
                                }
                            }
                        } else {
                            //没有选择团长
                            if (item.id == express[i].id) {
                                item.if = express[i].if == 1 ? 1 : 0;
                                item.newst = express[i].newst == 1 ? 1 : 0;
                                item.status = express[i].status == 1 ? 1 : 0;
                                item.o_price = express[i].o_price;
                                item.price = express[i].price;
                                item.proType = express[i].proType;
                                item.stock_number = express[i].stock_number > 0 ? express[i].stock_number : 0;
                                if (item.status == 1) {
                                    items.push(item);
                                } else {
                                    items2.push(item);
                                }
                            }
                        }
                    });
                }
                for (var j = 0; j < items.length; j++) {
                    items[j]["select"] = 0;
                }
                let cart_count = 0;
                for (var i = 0; i < items.length; i++) {
                    cart_count += Number(items[i]["count"]);
                }
                wx.setStorage({
                    key: "cart_count",
                    data: cart_count
                });
                wx.setStorage({
                    key: "cart",
                    data: items
                });
                wx.setStorage({
                    key: "invalid",
                    data: items2
                });
                this.setData({
                    items: items,
                    items2: items2,
                    money: 0,
                    discount: 0,
                    o_money: 0
                });
                let money_xx = that.data.order_start * 100 - that.data.money * 100;
                that.setData({
                    money_xx: money_xx / 100
                });
                setTimeout(function() {
                    that.select_all();
                }, 200);
            }
        });
    },
    save_count: function(e) {
        var that = this;
        //不是会员
                if (that.data.vipStatus <= 0) {
            //付费会员才可以购买
            if (e.currentTarget.dataset.onlyvip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        var index = e.currentTarget.dataset.index;
        var items = that.data.items;
        items[index]["count"] = parseInt(e.detail.value);
        let all_money = 0;
        if (items[index].stock_number < parseInt(e.detail.value)) {
            wx.showModal({
                title: "提示",
                content: "商品数量不能超过库存"
            });
            items[index]["count"] = items[index].stock_number;
            return;
        }
        items.forEach((item, i) => {
            if (i != index) {
                all_money += Number((item.price * item.count).toFixed(2));
            }
        });
        let all_price = Number(all_money) + Number(parseInt(e.detail.value) * items[index].price);
        that.setData({
            money: all_price
        });
        let money_xx = that.data.order_start * 100 - that.data.money * 100;
        that.setData({
            money_xx: money_xx / 100
        });
        that.setData({
            items: items
        });
        wx.setStorage({
            key: "cart",
            data: items
        });
        let cart_count = 0;
        for (var i = 0; i < items.length; i++) {
            cart_count += Number(items[i]["count"]);
        }
        wx.setStorage({
            key: "cart_count",
            data: cart_count
        });
    },
    reduce_count: function(e) {
        var that = this;
        //不是会员
                if (that.data.vipStatus <= 0) {
            //付费会员才可以购买
            if (e.currentTarget.dataset.onlyvip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        var index = e.currentTarget.dataset.index;
        var items = that.data.items;
        var money = parseFloat(that.data.money);
        var o_money = parseFloat(that.data.o_money);
        var discount = parseFloat(that.data.discount);
        if (items[index]["count"] > 1) {
            items[index]["count"]--;
            if (items[index]["select"] == 0) {
                items[index]["select"] = 1;
                if (that.data.features.memberVip == 1 && items[index].is_vip == 1 && that.data.vipStatus == 1 || items[index].is_mem_level == 1) {
                    money = money + parseFloat(items[index]["count"]) * parseFloat(items[index]["vip_price"]);
                } else {
                    money = money + parseFloat(items[index]["count"]) * parseFloat(items[index]["price"]);
                }
                o_money = o_money + parseFloat(items[index]["count"]) * parseFloat(items[index]["o_price"]);
                discount = o_money - money;
            } else {
                if (that.data.features.memberVip == 1 && items[index].is_vip == 1 && that.data.vipStatus == 1 || items[index].is_mem_level == 1) {
                    money -= parseFloat(items[index]["vip_price"]);
                } else {
                    money -= parseFloat(items[index]["price"]);
                }
                o_money -= parseFloat(items[index]["o_price"]);
                discount = o_money - money;
            }
        }
        this.setData({
            items: items,
            money: money.toFixed(2),
            o_money: o_money.toFixed(2),
            discount: discount.toFixed(2)
        });
        let money_xx = that.data.order_start * 100 - that.data.money * 100;
        that.setData({
            money_xx: money_xx / 100
        });
        // 判断起购条件
                that.startBuyCondition(money);
        wx.setStorage({
            key: "cart",
            data: items
        });
        let cart_count = 0;
        for (var i = 0; i < items.length; i++) {
            cart_count += Number(items[i]["count"]);
        }
        wx.setStorage({
            key: "cart_count",
            data: cart_count
        });
    },
    add_count: function(e) {
        var that = this;
        //不是会员
                if (that.data.vipStatus <= 0) {
            //付费会员才可以购买
            if (e.currentTarget.dataset.onlyvip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        that.add_count_ch(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {}
            });
        }
    },
    getDatashow() {
        let that = this;
        common.request({
            endpoint: "Member/member/message_times",
            method: "post",
            data: {
                openid: wx.getStorageSync("user").openid,
                message_times: 1
            },
            success: res => {}
        });
    },
    add_count_ch: function(e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var items = that.data.items;
        var money = parseFloat(that.data.money);
        var o_money = parseFloat(that.data.o_money);
        var discount = parseFloat(that.data.discount);
        items[index]["count"]++;
        if (items[index].stock_number < items[index]["count"]) {
            wx.showModal({
                title: "提示",
                content: "商品数量不能超过库存"
            });
            items[index]["count"] = items[index].stock_number;
            return;
        }
        if (items[index]["select"] == 0) {
            items[index]["select"] = 1;
            if (that.data.features.memberVip == 1 && items[index].is_vip == 1 && that.data.vipStatus == 1 || items[index].is_mem_level == 1) {
                money = money + parseFloat(items[index]["count"]) * parseFloat(items[index]["vip_price"]);
            } else {
                money = money + parseFloat(items[index]["count"]) * parseFloat(items[index]["price"]);
            }
            o_money = o_money + parseFloat(items[index]["count"]) * parseFloat(items[index]["o_price"]);
            discount = o_money - money;
        } else {
            if (that.data.features.memberVip == 1 && items[index].is_vip == 1 && that.data.vipStatus == 1 || items[index].is_mem_level == 1) {
                money += parseFloat(items[index]["vip_price"]);
            } else {
                money += parseFloat(items[index]["price"]);
            }
            o_money += parseFloat(items[index]["o_price"]);
            discount = o_money - money;
        }
        this.setData({
            items: items,
            money: money.toFixed(2),
            o_money: o_money.toFixed(2),
            discount: discount.toFixed(2)
        });
        let money_xx = that.data.order_start * 100 - that.data.money * 100;
        that.setData({
            money_xx: money_xx / 100
        });
        //判断起购条件
                that.startBuyCondition(money);
        wx.setStorage({
            key: "cart",
            data: items
        });
        let cart_count = 0;
        for (var i = 0; i < items.length; i++) {
            cart_count = Number(cart_count) + Number(items[i]["count"]);
        }
        wx.setStorage({
            key: "cart_count",
            data: cart_count
        });
    },
    select_one: function(e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var items = that.data.items;
        var select_all = that.data.select_all;
        var money = parseFloat(that.data.money);
        var o_money = parseFloat(that.data.o_money);
        var discount = parseFloat(that.data.discount);
        if (items[index]["select"] == 1) {
            items[index]["select"] = 0;
            if (that.data.features.memberVip == 1 && items[index].is_vip == 1 && that.data.vipStatus == 1 || items[index].is_mem_level == 1) {
                money -= parseFloat(items[index]["count"]) * parseFloat(items[index]["vip_price"]);
            } else {
                money -= parseFloat(items[index]["count"]) * parseFloat(items[index]["price"]);
            }
            o_money -= parseFloat(items[index]["count"]) * parseFloat(items[index]["o_price"]);
            discount = o_money - money;
        } else {
            items[index]["select"] = 1;
            if (that.data.features.memberVip == 1 && items[index].is_vip == 1 && that.data.vipStatus == 1 || items[index].is_mem_level == 1) {
                money += parseFloat(items[index]["count"]) * parseFloat(items[index]["vip_price"]);
            } else {
                money += parseFloat(items[index]["count"]) * parseFloat(items[index]["price"]);
            }
            o_money += parseFloat(items[index]["count"]) * parseFloat(items[index]["o_price"]);
            discount = o_money - money;
        }
        var total = 0;
        // 判断起购条件
                that.startBuyCondition(money);
        that.setData({
            items: items,
            money: money.toFixed(2),
            o_money: o_money.toFixed(2),
            discount: discount.toFixed(2)
        });
        let money_xx = that.data.order_start * 100 - that.data.money * 100;
        that.setData({
            money_xx: money_xx / 100
        });
        var items = that.data.items;
        for (var i = 0; i < items.length; i++) {
            if (items[i]["select"] == 1) {
                total++;
            } else {
                break;
            }
        }
        if (total == items.length) {
            select_all = 1;
        } else {
            select_all = 0;
        }
        that.setData({
            select_all: select_all
        });
    },
    select_all: function() {
        var that = this;
        var select_all = that.data.select_all;
        var items = that.data.items;
        var money = parseFloat(that.data.money);
        var o_money = parseFloat(that.data.o_money);
        var discount = parseFloat(that.data.discount);
        if (select_all == 1) {
            for (var i = 0; i < items.length; i++) {
                items[i]["select"] = 0;
                select_all = 0;
                money = 0;
                o_money = 0;
                discount = 0;
            }
        } else {
            money = 0;
            for (var i = 0; i < items.length; i++) {
                items[i]["select"] = 1;
                select_all = 1;
                if (that.data.features.memberVip == 1 && items[i].is_vip == 1 && that.data.vipStatus == 1 || items[i].is_mem_level == 1) {
                    money += parseFloat(items[i]["vip_price"]) * parseFloat(items[i]["count"]);
                } else {
                    money += parseFloat(items[i]["price"]) * parseFloat(items[i]["count"]);
                }
                o_money += parseFloat(items[i]["o_price"]) * parseFloat(items[i]["count"]);
                discount = o_money - money;
            }
        }
        // 判断起购条件
                that.startBuyCondition(money);
        that.setData({
            items: items,
            select_all: select_all,
            money: money.toFixed(2),
            o_money: o_money.toFixed(2),
            discount: discount.toFixed(2)
        });
        let money_xx = that.data.order_start * 100 - that.data.money * 100;
        that.setData({
            money_xx: money_xx / 100
        });
    },
    del_cart: function() {
        var that = this;
        var items = that.data.items;
        var arr = [];
        var money = parseFloat(that.data.money);
        var o_money = parseFloat(that.data.o_money);
        var discount = parseFloat(that.data.discount);
        var num = 0;
        for (var i = 0; i < items.length; i++) {
            if (items[i]["select"] == 0) {
                arr.push(items[i]);
            } else {
                num++;
                money = 0;
                o_money = 0;
                discount = 0;
            }
        }
        that.setData({
            items: arr,
            money: money.toFixed(2),
            o_money: o_money.toFixed(2),
            discount: discount.toFixed(2)
        });
        let money_xx = that.data.order_start * 100 - that.data.money * 100;
        that.setData({
            money_xx: money_xx / 100
        });
        that.startBuyCondition(money.toFixed(2));
        wx.setStorage({
            key: "cart",
            data: arr
        });
        let cart_count = 0;
        for (var i = 0; i < arr.length; i++) {
            cart_count += Number(arr[i]["count"]);
        }
        wx.setStorage({
            key: "cart_count",
            data: cart_count
        });
        //提示删除成功
                if (num > 0) {
            wx.showToast({
                title: "删除成功",
                icon: "none"
            });
        }
    },
    settlement: function(e) {
        let that = this;
        let source = e.currentTarget.dataset.source;
        let index = e.currentTarget.dataset.index;
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {
                    that.getDatashow();
                },
                fail(err) {},
                complete() {
                    that.settlement_ch(source, index);
                }
            });
        } else {
            that.settlement_ch(source, index);
        }
    },
    settlement_ch: function(source, index) {
        var that = this;
        let list = source == 1 ? that.data.localPlist[index].products : that.data.platform.products;
        let arr = [];
        list.forEach(item => {
            if (item.checked == 1) {
                let data = {
                    id: item.item_id,
                    count: item.num
                };
                arr.push(data);
            }
        });
        let sku_item = that.buildItem(arr);
        let pathUrl;
        if (list.findIndex(item => item.checked == 1) != -1) {
            if (source == 1) {
                pathUrl = "/localLifePackage/pages/orderPay/orderPay?sku_item=" + sku_item + "&id=" + that.data.localPlist[index].business.id + "&come=1";
            } else {
                if (that.data.group_id) {
                    pathUrl = "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 1 + "&group_id=" + that.data.group_id + "&come=1";
                } else {
                    pathUrl = "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 1 + "&come=1";
                }
            }
        } else {
            wx.showModal({
                title: "提示",
                content: "请勾选商品"
            });
        }
        that.setData({
            repeatBind: false
        });
        wx.navigateTo({
            url: pathUrl
        });
    },
    buildItem: function(items) {
        return items.map(item => {
            return item.id + "," + item.count + "," + item.credit_sent + "," + item.proType;
        }).join("|");
    },
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_header: res.extra.color_header,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    order_start: res.extra.order_start,
                    order_start_switch: res.extra.order_start_switch,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2
                });
                // 处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
            }
        });
    },
    startBuyCondition(money) {
        var that = this;
        //判断是否达到起购价
                var moneyNum = Number(money);
        var startNum = Number(that.data.order_start);
        if (that.data.order_start_switch == "1") {
            //起购打开
            if (moneyNum >= startNum) {
                //达到起购价
                that.setData({
                    isPayStatus: true,
                    defferNum: "去结算"
                });
            } else {
                //未达到起购价
                that.setData({
                    isPayStatus: false,
                    defferNum: moneyNum == 0 ? "满￥" + startNum + "元起购" : "差" + (startNum - moneyNum).toFixed(2) + "元起购"
                });
            }
        } else {
            //起购关闭
            that.setData({
                isPayStatus: true,
                defferNum: "去结算"
            });
        }
    },
    //跳转分类页
    goToAddProduct(e) {
        wx.reLaunch({
            url: "/pages/classfit/classfit"
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "21" || v.type == "22" || v.type == "101") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    }
});